﻿
using System.IO;
using CatEars.Core.FileFormat.Ini;

namespace CatEars.Core.Data.KvParam
{
#pragma warning disable 1591
    public class IniSettingProvider : SettingProvider
    {
        /// <summary>
        /// Ini格式定义
        /// </summary>
        public IniDefine IniDefine { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        public IniSettingProvider()
        {
            IniDefine = new IniDefine();
            FileExt = ".ini";
        }

        /// <summary>
        /// 默认文件夹
        /// </summary>
        /// <returns></returns>
        protected override string GetDefaultFolderName()
        {
            return Path.Combine(AppEnv.ExeDirPath, "Config");
        }

        /// <summary>
        /// 创建参数对象的方法
        /// </summary>
        /// <returns></returns>
        public override ZSettingParams CreateParam()
        {
            IniSettingParams r = new IniSettingParams();
            return r;
        }

        /// <summary>
        /// 加载参数
        /// </summary>
        /// <param name="strFilePath">存储路径</param>
        /// <returns>加载的参数</returns>
        protected override ZSettingParams LoadFromPath(string strFilePath)
        {
            try
            {
                string strFilePath0 = strFilePath;
                IniFile iniFile = new IniFile(strFilePath0);
                IniSettingParams r = new IniSettingParams(iniFile);
                return r;
            }
            catch
            {
                if (!SafeMode) throw;
            }
            ZSettingParams p = base.CreateParam();
            return p;
        }
        /// <summary>
        /// 保存参数
        /// </summary>
        /// <param name="strFilePath">存储路径</param>
        /// <param name="p">要保存的参数</param>
        protected override void SaveToPath(string strFilePath, ZSettingParams p)
        {
            string strFilePath0 = strFilePath;
            try
            {
                if (p == null || p.Count == 0)
                {
                    if (File.Exists(strFilePath0))
                    {
                        File.Delete(strFilePath0);
                    }
                    return;
                }
                IniSettingParams pIni = p as IniSettingParams;
                if (pIni == null)
                {
                    // p 不是 IniSettingParams 类型的 进行一次深拷贝
                    pIni = new IniSettingParams();
                    p.CopyTo(pIni);
                }
                pIni.IniFile.Save(strFilePath0, IniDefine);
            }
            catch
            {
                if (!SafeMode) throw;
            }
        }
    }
}
